package com.sx.controller;


import com.github.pagehelper.PageInfo;
import com.sx.domain.ResponseResult;
import com.sx.domain.Role;
import com.sx.domain.User;
import com.sx.domain.UserVo;
import com.sx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;
    /**
     * 用户分页多条件查询方法
     */
    @RequestMapping("/findAllUserByPage")
    public ResponseResult findAllUserByPage(UserVo userVo) {
        PageInfo allUserByPage = userService.findAllUserByPage(userVo);
        return new ResponseResult(true, 200, "用户分页多条件查询成功", allUserByPage);
    }

    /**
     * 修改用户状态
     */
    @RequestMapping("/updateUserStatus")
    public ResponseResult updateUserStatus(int id,String status) {
        if("ENABLE".equalsIgnoreCase(status)){
            status = "DISABLE";
        }else{
            status = "ENABLE";
        }
        userService.updateUserStatus(id, status);
        ResponseResult responseResult = new ResponseResult(true,200,"响应成功",status);
        return responseResult;
    }


    /**
     * 用户登录
     */
    @RequestMapping("/login")//post 请求要加@RequestParam
    public ResponseResult login(User user , HttpServletRequest  request) {
        User login = userService.login(user);

        if (login != null){
            // 登录成功后将用户状态修改为ENABLE
            userService.updateUserStatus(login.getId(), "ENABLE");
            
            //保存用户id及access_token到session中
            HttpSession session = request.getSession();
            UUID access_token = UUID.randomUUID();
            session.setAttribute("access_token",access_token);
            session.setAttribute("user_id",login.getId());

            //将查询出来的信息响应给前台
            HashMap<String, Object> Map = new HashMap<>();
            Map.put("access_token",access_token);
            Map.put("user_id",login.getId());
            return new ResponseResult(true,200,"用户登录成功",Map);


        }else {
            return new ResponseResult(false,400,"用户登录失败",null);
        }
    }
    /**
     * 查询当前用户所拥有的角色
     */
    @RequestMapping("/findUserRelationRoleById")
    public ResponseResult getUserRelationRoleById(Integer id) {
        List<Role> roleList = userService.findUserRelationRoleById(id);
        return new ResponseResult(true,200,"查询当前用户所拥有的角色成功",roleList);
    }
    
    /**
     * 用户注册
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ResponseResult register(@RequestBody User user) {
        try {
            // 参数校验
            if (user.getPhone() == null || user.getPhone().trim().isEmpty()) {
                return new ResponseResult(false, 400, "手机号不能为空", null);
            }
            
            if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
                return new ResponseResult(false, 400, "密码不能为空", null);
            }
            
            // 检查手机号是否已存在
            User existingUser = userService.findByPhone(user.getPhone());
            if (existingUser != null) {
                return new ResponseResult(false, 400, "该手机号已被注册", null);
            }
            
            // 执行注册
            userService.register(user);
            
            return new ResponseResult(true, 200, "注册成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(false, 500, "注册失败: " + e.getMessage(), null);
        }
    }

    /**
     *  获取用户拥有的菜单权限
     */
    @RequestMapping("/userContextRole")
    public ResponseResult userContextRole(@RequestBody UserVo userVo) {
        userService.userContextRole(userVo);
        return new ResponseResult(true,200," 获取用户拥有的菜单权限成功",null);
    }

    /**
     * 获取用户权限信息
     */
    @RequestMapping("/getUserPermissions")
    public ResponseResult getUserPermissions(HttpServletRequest  request) {
        //获取请求头的 token（优先从请求头获取，如果没有则从参数获取）
        String authorization = request.getHeader("Authorization");
        if (authorization == null) {
            authorization = request.getParameter("Authorization");
        }
        
        //获取session中的token
        Object accessTokenObj = request.getSession().getAttribute("access_token");
        String accessToken = accessTokenObj != null ? accessTokenObj.toString() : null;
        
        // 添加调试信息
        System.out.println("Request Authorization: " + authorization);
        System.out.println("Session Access Token: " + accessToken);
        System.out.println("Tokens Match: " + (authorization != null && authorization.equals(accessToken)));
        
        //判断token是否一致
        if (authorization != null && authorization.equals(accessToken)){
            //获取用户id
            Object userIdObj = request.getSession().getAttribute("user_id");
            Integer userid = userIdObj != null ? (Integer) userIdObj : null;
            System.out.println("User ID from session: " + userid);
            
            if (userid == null) {
                return new ResponseResult(false,400,"用户权限信息获取失败，用户未登录",null);
            }
            //调用service，进行菜单查询
            return userService.getUserPermissions(userid);
        }else {
            return new ResponseResult(false,400,"用户权限信息获取失败",null);
        }
    }


}